package cc.eddic.pratice.programmingparadigms.exam.impl;

import cc.eddic.pratice.programmingparadigms.emp02list.impl.ResultListGcsImpl;
import cc.eddic.pratice.programmingparadigms.exam.Model.AnswerModel;
import cc.eddic.pratice.programmingparadigms.exam.QuestionBankService;
import cc.eddic.pratice.programmingparadigms.exam.QuestionType;
import cc.eddic.pratice.programmingparadigms.exam.domain.Category;
import cc.eddic.pratice.programmingparadigms.exam.domain.Option;
import cc.eddic.pratice.programmingparadigms.exam.domain.Question;
import cc.eddic.pratice.programmingparadigms.exam.domain.SubCategory;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

public class QuestionBankServiceLxImpl extends QuestionBankServiceImpl implements QuestionBankService {
    private static final Logger log = LoggerFactory.getLogger(ResultListGcsImpl.class);
    @Override
    public List<Question> importQuestions(String questionTextFile) {
        String fileContent = getQuestionFileContent();
        String[] a=fileContent.split("\n");
        List<Question> questionList = new ArrayList<>();
        for(String s:a){
            int count = s.indexOf("、");
            if(s.length()==0){
                continue;
            }
            if(Character.isDigit(s.charAt(0))){
                String no = s.substring(0,count);
                String des = s.substring(count+1);
                System.out.print(no);
                Question q1 = new Question(Integer.parseInt(no), des, QuestionType.SINGLE_CHOICE);
                questionList.add(q1);
            }else if(s.charAt(0)>='a' && s.charAt(0)<='z' || s.charAt(0)>='A' && s.charAt(0)<='Z'){
                String choice=s.substring(0,count);
                String answer=s.substring(count+1);
                questionList.get(questionList.size()-1).add(new Option(answer,choice.charAt(0),false));
            }
        }
        return questionList;
    }

    @Override
    public List<Question> importCorrectAnswers(String correctAnswerTextFile) {
        Map<Integer, Character> answerMap=readCorrectAnswers2("");
        List<Question> questionList=importQuestions("");
        for(Question q:questionList){
            if(!answerMap.containsKey(q.getNo())){
                continue;
            }
            char choice=answerMap.get(q.getNo());
            Option option=q.getOptions().stream().filter(o->o.getChoice()==(choice)).findFirst()
                    .orElseThrow(()->new IllegalArgumentException("没找到该选项"));
            option.changeToCorrectAnswer();
            if (log.isDebugEnabled()) log.debug("问题{},问题中的正确的选项: {}，问题中的选项状态: {}", q.getNo(),option.getChoice(),option.isCorrectAnswer());
        }
        return questionList;
    }

    @Override
    public List<AnswerModel> readCorrectAnswers(String correctAnswerTextFile) {
        String answer="1\t2\t3\t4\t5\t6\t7\t8\t9\t10\n" +
                "B\tC\tA\tC\tD\tB\tB\tA\tD\tB\n" +
                "11\t12\t13\t14\t15\t16\t17\t18\t19\t20\n" +
                "B\tC\tA\tC\tA\tB\tD\tC\tD\tB\n" +
                "21\t22\t23\t24\t25\n" +
                "A\tD\tA\tC\tB";
        List<AnswerModel> answerModelList = new ArrayList<>();
        List<Integer> noList=new ArrayList();
        List<Character> choiceList=new ArrayList();
        String[] ans=answer.split("\n");
        for(String s:ans){
            String[] every=s.split("\t");
            for(String i:every){
                if(Character.isDigit(i.charAt(0))){
                    noList.add(Integer.parseInt(i));
                }else if(Character.isLetter(i.charAt(0))){
                    choiceList.add(i.charAt(0));
                }
            }
        }
        for(int i=0;i<noList.size();i++){
            AnswerModel answerModel=new AnswerModel(noList.get(i),choiceList.get(i));
            answerModelList.add(answerModel);
        }
        return answerModelList;
    }
    @Override
    public Map<Integer,Character> readCorrectAnswers2(String correctAnswerTextFile){
        String[] file = getAnswerFileContent().split("\n");
        Map<Integer,Character> result = new HashMap<>();
        for(int i=0;i<file.length;i+=2){
            String[] no=file[i].split("\t");
            String[] cho=file[i+1].split("\t");
            for(int j=0;j<no.length;j++){
                int number=Integer.parseInt(no[j]);
                char choice=cho[j].charAt(0);
                result.put(number,choice);
                if (log.isDebugEnabled()) log.debug("存进去的正确答案: {}", result.get(number));
            }
        }
        return result;
    }

    @Override
    public List<Question> importCategories(String categoryExcelFile) {
        try {
            HashMap<String, String> categoryMap = new HashMap<>();
            categoryMap.put("基础", "软件开发基础");
            categoryMap.put("HTML", "软件开发基础");
            categoryMap.put("SQL", "软件开发基础");
            categoryMap.put("DOS", "软件开发基础");
            categoryMap.put("Linux", "软件开发基础");
            categoryMap.put("数学", "软件开发基础");

            categoryMap.put("Word", "办公软件");
            categoryMap.put("Excel", "办公软件");

            categoryMap.put("代码", "代码");


            FileInputStream file = new FileInputStream(categoryExcelFile);
            Workbook workbook = new XSSFWorkbook(file);

            ArrayList<Question> questionList = (ArrayList<Question>) importQuestions("");


            Sheet categorySheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = categorySheet.rowIterator();

            rowIterator.next();
            Row rowSubCategory = rowIterator.next();

            while(rowIterator.hasNext()) {
                try {
                    Row row = rowIterator.next();
                    CellType cellType = row.getCell(0).getCellType();
                    if (cellType == CellType.STRING) {
                        break;
                    }
                    int no =  (int) row.getCell(0).getNumericCellValue();


                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
                        if (cell.getNumericCellValue() == 1) {
                            int columnIndex = cell.getColumnIndex();
                            String nameSubCategory = rowSubCategory.getCell(columnIndex).getRichStringCellValue().getString();
                            SubCategory subcategory = new SubCategory(nameSubCategory);
                            subcategory.setCategory(new Category(categoryMap.get(nameSubCategory)));
                            questionList.get(no - 1).setSubCategory(subcategory);
                            break;
                        }
                    }

                }
                catch (NumberFormatException e) {
                    break;
                }
            }

            return questionList;
        }
        catch (FileNotFoundException e) {
            log.error("importCategories FileInputStream FileNotFoundException\n");
        } catch (IOException e) {
            log.error("importCategories XSSFWorkbook IOException\n");
        }

        return null;

    }


}
